<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 搜索 -->
                <div style="display: flex;">
                    <div>
                        <el-date-picker :default-time="defaultTime" style="width: 340px;height:30px" v-model="timeTypeTime"
                        @change="timeTypeTime_btn" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"
                        format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                    </div>
                    <el-select style="width: 120px;margin-left: 10px;" v-model="find_data.tradeStatus" placeholder="">
                        <el-option  label="支出" :value="'PAY'" />
                        <el-option  label="收入" :value="'INCOME'" />
                    </el-select>
                    <el-select clearable style="width:140px;margin-left: 10px;" v-model="find_data.balType" placeholder="金额类型">
                        <el-option v-for="item in getCusBalanceTypes_list" :key="item.id" :label="item.text"
                        :value="item.id" />
                    </el-select>
                    <el-select clearable style="width:140px;margin-left: 10px;" v-model="find_data.payType" placeholder="交易记录类型">
                        <el-option v-for="item in getCusTradeTypes_list" :key="item.id" :label="item.text"
                        :value="item.id" />
                    </el-select>
                    <el-select  filterable remote :filter-method="handleFilter" clearable style="width:140px;margin-left: 10px;" v-model="find_data.userId" placeholder="客户">
                        <el-option v-for="item in serviceCenterfindComboCusList_list" :key="item.userId" :label="item.cusCompanySimpleName"
                        :value="item.userId" />
                    </el-select>
                    <el-input style="width: 200px;margin-left: 10px;" v-model="find_data.note" placeholder="订单详情" clearable
                      />


                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <!-- <div style="margin-top:10px;">
                    <el-button @click="add_btn" type="primary" icon="SuccessFilled">添加</el-button>
                    <el-button @click="up_btn" type="warning" icon="WarnTriangleFilled">修改</el-button>
                    <el-button @click="del_btn" type="danger" icon="CircleCloseFilled">删除</el-button>
                </div> -->
            </template>
            <div>
                <el-table border @selection-change="selection_change_btn" height="67vh" ref="multipleTableRef"
                    :data="list_data" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                            <template v-if="item.field == 'balType'" #="{ row, column, $index }">
                                <span>{{balType_api(row.balType) }}</span>

                            </template>
                            <template v-if="item.field == 'payType'" #="{ row, column, $index }">
                                <span>{{payType_api(row.payType) }}</span>

                            </template>
                            

                        </el-table-column>
                    </template>
                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                    :page-sizes="[20, 50, 100, 200]" :background="true"
                    layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:75px;z-index: 2;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <!-- 添加修改 -->
        <el-dialog style="margin-top:5vh" v-model="add_off" :title="title" width="65%" :close-on-click-modal='false'>
            <el-form :model="add_data" label-width="140px" label-suffix="：">
                <el-form-item label="常用地址" prop="address" :rules="[
                    { required: false, message: '常用地址', trigger: 'change' },
                ]">
                    <el-input @click="showMap()" style="width: 100%" v-model="add_data.address" placeholder="请选择常用地址" />
                </el-form-item>
                <el-row :gutter="20">

                    <el-col :span="12">
                        <el-form-item label="位置简称" prop="stationName" :rules="[
                            {
                                required: false,
                                message: '请填写位置简称',
                                trigger: 'change',
                            },
                        ]">
                            <el-input style="width: 100%" v-model="add_data.stationName" placeholder="请填写位置简称">

                            </el-input>
                        </el-form-item>

                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" prop="hotelLinkPhone" :rules="[
                            {
                                required: false,
                                message: '联系电话',
                                trigger: 'change',
                            },
                        ]">
                            <el-input style="width: 100%" v-model="add_data.hotelLinkPhone" placeholder="请填写联系电话">

                            </el-input>
                        </el-form-item>

                    </el-col>
                </el-row>
                <el-form-item label="备注" prop="nameNote" :rules="[
                    {
                        required: false,
                        message: '请填写备注',
                        trigger: 'change',
                    },
                ]">

                    <el-input v-model="add_data.nameNote" :autosize="{ minRows: 4, maxRows: 6 }" type="textarea"
                        placeholder="请填写备注" />
                </el-form-item>


            </el-form>
            <div style="margin-left:55vw;margin-top:8px;display:flex"> <el-button @click="ok_btn()"
                    type="primary">确认提交</el-button>
            </div>

        </el-dialog>
        <!-- 地图弹窗 -->
        <el-dialog style="margin-top:10vh;height:80vh;overflow: hidden;" v-model="map_off" title="常用地址:" width="80%"
            :close-on-click-modal='false'>
            <div class="div_map">
                <div class="map_input">
                    <el-input @input="map_change" id='tipinput' style="width:40%" v-model="map_address"
                        placeholder="请输入常用地址">
                        <template #prepend>常用地址:</template>
                    </el-input>
                    <el-button @click="map_ok_btn" type="primary">确认</el-button>
                </div>
                <div v-if="map_address_list.length > 0" class="map_input2">
                    <div style="width:40%;background:#fff;margin-left:20px;padding: 10px;font-weight: 700;">
                        <div @click="map_list_btn(item)" class="div_bg" v-for="(item, index) in map_address_list"
                            :key="index" style="margin-top: 10px;">
                            {{ item.district }}-{{ item.address }}-{{ item.name }}
                        </div>
                    </div>
                </div>
                <div id="myMap" style="height: 65vh; width: 100%">
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import * as XLSX from 'xlsx';
import Sortable from 'sortablejs';
import AMapLoader from "@amap/amap-jsapi-loader"
import { GET_TOKEN } from '@/utils/token.js'
import { ref, reactive, onMounted, computed } from 'vue'
import {
    adupPrivateSet, getPrivateSetList, getCusTradeTypes, getCusTradeForCompany, getCusBalanceTypes, serviceCenterfindComboCusList,
    
} from '@/api/information_center.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { importCusCheckInData, line2treeData, securityJsCode, key, } from '@/utils/common.js'
import CircularJSON from 'circular-json'
onMounted(async () => {


    getPrivateSetList({
        find: '常用地址',
        page: {
            pageNum: 1,
            pageSize: 999,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            table_data_list_new.value = table_data_list
        }
    })


    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);

            // 重新赋值给列数组
            // let cols = that.U.scopy(that.fields);
            // let list = cols.filter(it => { return it.show; });
            // that.$emit('saveSet', {dgName: that.dgName, cols: list});
        }
    })

    getCusBalanceTypes({}).then(res => {
        getCusBalanceTypes_list.value = res.data
    })
    getCusTradeTypes({}).then(res => {
        getCusTradeTypes_list.value = res.data
    })
    serviceCenterfindComboCusList({
    page: {
        pageNum: 1,
        pageSize: 9999,
    },}).then(res => {
        serviceCenterfindComboCusList_list.value = res.data
        serviceCenterfindComboCusList_list2.value = res.data
    })
    timeTypeTime.value = [new_day(), to_day()]
    find_data.stime = new_day()
    find_data.etime = to_day()
    await list_api()




})
const serviceCenterfindComboCusList_list = ref([])
const serviceCenterfindComboCusList_list2 = ref([])
const getCusBalanceTypes_list = ref([])
const getCusTradeTypes_list = ref([])
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]
const timeTypeTime = ref('')
const timeTypeTime_btn = (e) => {
    if (e) {
        timeTypeTime.value = e
        find_data.stime = timeTypeTime.value[0]
        find_data.etime = timeTypeTime.value[1]
    } else {
        timeTypeTime.value = ''
        find_data.stime = ''
        find_data.etime = ''
    }
}
const to_day = () => {
    let today = new Date();
    let tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 30);

    let year = tomorrow.getFullYear();
    let month = tomorrow.getMonth() + 1; // 月份是从 0 到 11，所以需要加上 1
    let day = tomorrow.getDate();

    // 如果月份或日期小于 10，则在前面补零
    if (month < 10) {
        month = '0' + month;
    }

    if (day < 10) {
        day = '0' + day;
    }

    let formattedDate = `${year}-${month}-${day} 23:59:59`;
    return formattedDate
}
const balType_api = (e) => {
    let data =''
    for (let i = 0; i < getCusBalanceTypes_list.value.length; i++){
        if (e == getCusBalanceTypes_list.value[i].id) {
            data = getCusBalanceTypes_list.value[i].text
        }
    }
    return data
}
const payType_api = (e) => {
    let data =''
    for (let i = 0; i < getCusTradeTypes_list.value.length; i++){
        if (e == getCusTradeTypes_list.value[i].id) {
            data = getCusTradeTypes_list.value[i].text
        }
    }
    return data
}
const handleFilter = (value) => {
    // 自定义筛选逻辑
    if (value) {
        let results = serviceCenterfindComboCusList_list2.value.filter(item => {
            for (let key in item) {
                if (typeof item[key] === 'string' && item[key].includes(value)) {
                    return true;
                }
            }
            return false;
        })
        if (results.length > 0) {
            serviceCenterfindComboCusList_list.value = results
        } else {
            serviceCenterfindComboCusList_list.value = []
        }
    } else {
        serviceCenterfindComboCusList_list.value = serviceCenterfindComboCusList_list2.value
    }
}
const new_day = () => {
    let today = new Date();

    let year = today.getFullYear();
    let month = today.getMonth() + 1; // 月份是从 0 到 11，所以需要加上 1
    let day = today.getDate();

    // 如果月份或日期小于 10，则在前面补零
    if (month < 10) {
        month = '0' + month;
    }

    if (day < 10) {
        day = '0' + day;
    }

    let formattedDate = `${year}-${month}-${day} 00:00:00`;
    return formattedDate
}
//#region 表格数据处理
const table_data_list = reactive([
    { label: '订单号', field: 'orderNum', width: 165, off: true },
    { label: '客户', field: 'realName', width: 165, off: true },
    { label: '手机号', field: 'loginPhone', width: 165, off: true },
    { label: '金额类型', field: 'balType', width: 165, off: true },
    { label: '交易记录类型', field: 'payType', width: 165, off: true },
    { label: '交易金额', field: 'amoney', width: 120, off: true },
    { label: '现金余额', field: 'cashBalance', width: 120, off: true },
    { label: '详情', field: 'assist', width: 400, off: true },
    { label: '备注', field: 'note', width: 400, off: true },
  
    { label: '添加时间', field: 'addTime', width: 165, off: true },
])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '常用地址',
        tbNum: "common_addresses",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion



//#region 分页列表
const list_data = ref([])
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    balType: 'TEAM_BALANCE',
    etime: '',
    note: '',
    payType: '',
    stime: '',
    tradeStatus: 'PAY',
    userId: '',

})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}

const list_api = () => {

    getCusTradeForCompany(find_data).then(res => {
        list_data.value = res.data.list.list
        total.value = res.data.list.total
    })
}
//#endregion

//#region 添加
const add_off = ref(false)

const title = ref('添加常用地址')
const add_data = reactive({
    id: "",
    belongCity: "",
    belongCounty: "",
    belongProvince: "",
    hotelLinkPhone: "",
    lat: "",
    lng: "",
    nameNote: "",
    stationName: "",
    stationType: "DIY",
})


const add_btn = () => {

    title.value = '添加常用地址'
    add_data.id = ''
    add_data.address = ''
    add_data.belongCity = ''
    add_data.belongCounty = ''
    add_data.belongProvince = ''
    add_data.hotelLinkPhone = ''
    add_data.lat = ''
    add_data.lng = ''
    add_data.nameNote = ''
    add_data.stationName = ''
    add_off.value = true

}


//#endregion

//#region 表格选择
const table_list = ref([])
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion
//#region 修改
const up_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }


    title.value = '修改常用地址'
    let coordinates = table_list.value[0].lngLat

    // 使用逗号分割字符串
    let splitCoordinates1 = coordinates.split(',')[0]
    let splitCoordinates2 = coordinates.split(',')[1]

    add_data.id = table_list.value[0].id
    add_data.address = table_list.value[0].address
    add_data.belongCity = table_list.value[0].belongCity
    add_data.belongCounty = table_list.value[0].belongCounty
    add_data.belongProvince = table_list.value[0].belongProvince
    add_data.lat = table_list.value[0].lat == 0?splitCoordinates2:table_list.value[0].lat
    add_data.lng = table_list.value[0].lng== 0?splitCoordinates1:table_list.value[0].lng
    add_data.hotelLinkPhone = table_list.value[0].hotelLinkPhone

    add_data.nameNote = table_list.value[0].nameNote
    add_data.stationName = table_list.value[0].stationName

    add_off.value = true
}
//#endregion

// 提交
const ok_btn = (e) => {




    adupStationList(add_data).then(res => {
        if (res.code == 1) {
            list_api()
            add_off.value = false
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
}

// 打开地图
const marker = ref('')
const map_off = ref(false)
const map_address = ref('')
const map_address_list = ref([])
const map_value = ref({})
const map_index = ref('')
const showMap = (e) => {
    map_index.value = e
    marker.value = ''
    map_address.value = ''
    map_address_list.value = []
    map_value.value = ''
    map_off.value = true


    // 地图
    window._AMapSecurityConfig = {
        securityJsCode: securityJsCode,
    }
    // 首次加载
    AMapLoader.load({
        key: key,
        version: '2.0',
        plugins: ['AMap.Driving', 'AMap.Geolocation', 'AMap.Scale', 'AMap.AutoComplete', 'AMap.PlaceSearch'],
    }).then((AMap) => {
        // 初始化-地图对象
        myMap.value = new AMap.Map('myMap', { zoom: 10, center: [104.065861, 30.657401] });
    }).catch(err => { console.log('高德地图加载失败：', err); });
}
const map_change = () => {
    let autoOptions = {
        city: '成都市'
    }
    var autoComplete = new AMap.Autocomplete(autoOptions);
    autoComplete.search(map_address.value, function (status, result) {
        // 搜索成功时，result即是对应的匹配数据
        map_address_list.value = result.tips.slice(0, 5)

    })
}
const map_list_btn = (e) => {
    map_address.value = e.district + '-' + e.address + '-' + e.name
    map_value.value = e

    myMap.value.panTo([e.location.lng, e.location.lat]);
    if (marker.value) {
        myMap.value.remove(marker.value);
    }
    myMap.value.setFitView();
    marker.value = new AMap.Marker({
        map: myMap.value,
        position: [e.location.lng, e.location.lat],
    });
    myMap.value.setFitView();
    myMap.value.add(marker.value);


}
const map_ok_btn = () => {


    const inputString = map_value.value.district
    // 使用正则表达式匹配并提取省、市、区
    const regex = /(.*?省)(.*?市)(.*?区)/
    const match = inputString.match(regex)

    if (match !== null) {
        const province = match[1] // 提取省份
        const city = match[2] // 提取城市
        const district = match[3]// 提取区县

        console.log("省份: " + province)
        console.log("城市: " + city)
        console.log("区县: " + district)
        add_data.belongCity = city
        add_data.belongCounty = district
        add_data.belongProvince = province
    } else {
        add_data.belongCity = ''
        add_data.belongCounty = ''
        add_data.belongProvince = ''
    }
    add_data.address = map_address.value

    add_data.lat = map_value.value.location.lat
    add_data.lng = map_value.value.location.lng
    map_off.value = false
}

//#region 删除
const del_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    ElMessageBox.confirm(
        '是否确认删除该地址?',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            delStationList({
                ids: [table_list.value[0].id]
            }).then(res => {
                if (res.code == 1) {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })

        })
        .catch((e) => {


        })

}
//#endregion

//#region 搜索
const search_btn = () => {

    list_api()
}
//#endregion
</script>

<style scoped lang='scss'>
.div_map {
    position: relative;
    left: 0;
    top: 0;
}

.map_input {
    width: 100%;
    position: absolute;
    z-index: 1;
    display: flex;
    justify-content: center;

}

.map_input2 {
    width: 100%;
    position: absolute;
    z-index: 1;
    display: flex;
    justify-content: center;
    top: 34px;

}

.div_bg:hover {


    background-color: darkgray;
}
</style>

<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}


.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
